package cn.kgc.shiroday03.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/6/3
 * @Description:
 */
@Configuration
public class GlobalShiroConfig {


    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean (DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        // 设置资源的拦截规则
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        //  /** url    authc  过滤器的简写形式  FormAuthenticationFilter
        map.put("/user/login","anon");
        // 释放静态资源
        map.put("/dist/**","anon");
        // 放行验证码请求
        map.put("/captcha/getCaptcha", "anon");

        //map.put("/**","authc");

        //需要已登录或“记住我”的用户才能访问  UserFilter
        map.put("/**","user");
        //设置登录页  login.jsp
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }



    @Bean
    public DefaultWebSecurityManager  defaultWebSecurityManager(Realm realm){

        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //设置免登录的时间
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        //自定义cookie
        SimpleCookie rememberMe = new SimpleCookie("rm");
        rememberMe.setMaxAge(60*60*24*7);
        cookieRememberMeManager.setCookie(rememberMe);
        defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager);

        defaultWebSecurityManager.setRealm(realm);
        return  defaultWebSecurityManager;
    }


    @Bean
    public  Realm  realm(){
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        hashedCredentialsMatcher.setHashIterations(20);
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        return customerRealm;
    }

}
